<?php

namespace backend\controllers;

use Yii;
use common\models\Admin;
use common\service\ConstantService;
use common\service\GlobalUrlService;
use yii\base\Module;
use yii\web\Controller;
use yii\web\Cookie;

/**
 * 控制器基类.
 * Class BaseController
 * @package backend\controllers
 */
class BaseController extends Controller
{
    /**
     * 加密所用到的盐,请勿修改,上线时在改
     * @var string
     */
    protected  $salt = 'a321df354sa35d1f';

    /**
     * 所记录的cookie名,请修改成项目名.
     * @var string
     */
    protected  $auth_cookie = "yii2admin";

    protected $allow_actions = [
        'admin/login'
    ];

    public function __construct($id, Module $module, array $config = [])
    {
        parent::__construct($id, $module, $config);
        $view  = \Yii::$app->view;
        $view->params['id'] = $id;
        $this->layout  = "main";
        $this->getView()->title = '后台管理系统';
    }

    /**
     * 这里要初始化权限
     * @param \yii\base\Action $action
     * @return bool
     */
    public function beforeAction($action)
    {
        if(in_array($action->getUniqueId(),$this->allow_actions))
        {
            return true;
        }

        $is_login = $this->checkLoginStatus();

        if(!$is_login)
        {
            if($this->isAjax())
            {
                $this->renderJson(['url'=>GlobalUrlService::buildAdminUrl('/admin/login')],'请重新登录',ConstantService::$response_fail);
            }
            $this->redirect(GlobalUrlService::buildAdminUrl('/admin/login'));
            return false;
        }
        // 这里要检查用户的权限,为rbac埋坑
        return true;
    }

    private function checkLoginStatus()
    {
        $cookie = $this->getCookie($this->auth_cookie);

        if(!$cookie)
        {
            return false;
        }

        list($uid, $token) = explode('#',$cookie);

        if($uid && preg_match('/^\d+$/',$uid))
        {
            $admin_user = Admin::findOne(['id'=>$uid]);

            if(!$admin_user)
            {
                $this->removeCookie($this->auth_cookie);
                return false;
            }

            // 这里要查询一下用户信息.
            $access_token = $this->genToken($admin_user);
            // 这里代表登录成功.
            if($access_token == $token)
            {
                $this->getView()->params['current_user'] = $admin_user;
                return true;
            }
        }
        return false;
    }

    /**
     * 生成密钥.
     * @param $admin
     * @return string
     */
    protected function genToken(Admin $admin)
    {
        return md5(md5(implode('-',[
                $admin->primaryKey,
                $admin['email'],
                $admin['created_time'],
                $admin['password'],
            ])) . $this->salt);
    }

    /**
     * 获取cookie值.
     * @param $cookie_name
     * @param string $default
     * @return mixed
     */
    private function getCookie($cookie_name,$default = '')
    {
        $cookies = Yii::$app->request->getCookies();
        return $cookies->getValue($cookie_name,$default);
    }

    /**
     * 删除Cookie
     * @param $cookie_name
     */
    protected function removeCookie($cookie_name)
    {
        $cookie_target = new Cookie([
            'name' => $cookie_name
        ]);
        $cookies = Yii::$app->response->cookies;
        $cookies->remove( $cookie_target );
    }

    /**
     * 添加cookie
     * @param string $cookie_name
     * @param string $value
     * @param int $expire
     */
    protected function addCookie($cookie_name,$value,$expire = 3600)
    {
        $cookies = Yii::$app->response->cookies;
        $cookies->add(new Cookie([
            'name' => $cookie_name,
            'value' => $value,
            'expire' => $expire? ( time() + $expire ):$expire,
            'path' => '/'
        ]));
    }

    /**
     * 判断是否为ajax请求.
     * @return bool|mixed
     */
    public function isAjax()
    {
        return Yii::$app->request->isAjax;
    }

    /**
     * 判断是否为post请求.
     * @return bool|mixed
     */
    public function isPost()
    {
        return Yii::$app->request->isPost;
    }

    /**
     * 判断是否为Get请求.
     * @return bool|mixed
     */
    public function isGet()
    {
        return Yii::$app->request->isGet;
    }

    /**
     * 获取queryString参数
     * @param string $key
     * @param string $default
     * @return array|string
     */
    public function get($key = '',$default = '')
    {
        $query = Yii::$app->request->getQueryParams();

        if(isset($query[$key]))
        {
            return $query[$key];
        }

        if(!$key)
        {
            return $query;
        }

        return $default;
    }

    /**
     * 获取post提交参数
     * @param string $key
     * @param string $default
     * @return array|string
     */
    public function post($key = '',$default = '')
    {
        $query = Yii::$app->request->getBodyParams();

        if(isset($query[$key]))
        {
            return $query[$key];
        }

        if(!$key)
        {
            return $query;
        }

        return $default;
    }

    /**
     * 渲染json请求.
     * @param array $data
     * @param string $msg
     * @param int $code
     */
    public function renderJson($data = [],$msg = '',$code = -1)
    {
        // 设置响应头信息.
        header('Content-type: application/json');

        echo json_encode([
            'data'  =>  $data,
            'msg'   =>  $msg,
            'code'  =>  $code,
            "req_id" =>  $this->geneReqId(),    // 防止缓存接口.
        ]);

        return Yii::$app->end();
    }

    /**
     * 获取唯一值.
     * @return string
     */
    private function geneReqId()
    {
        return uniqid();
    }
}